package com.ssy.lingxi.order.handler.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.order.model.bo.PayNodeBO;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.List;

/**
 * 将支付环节PayNodeBO，与表中的Jsonb字段进行转换
 * @author 万宁
 * @version 2.0.0
 * @date 2021-08-30
 */
@Converter(autoApply = true)
public class JpaJsonToPayNodeConverter implements AttributeConverter<List<PayNodeBO>, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public JpaJsonToPayNodeConverter() {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public String convertToDatabaseColumn(List<PayNodeBO> attribute) {
        try {
            return attribute == null ? OBJECT_MAPPER.writeValueAsString(new ArrayList<>()) : OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"支付环节转换Json错误");
        }
    }

    @Override
    public List<PayNodeBO> convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new ArrayList<>();
            }

            return OBJECT_MAPPER.readValue(dbData, new TypeReference<List<PayNodeBO>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库json字段转换支付环节实体错误");
        }
    }
}
